<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery_" :form="form">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="发货仓库">
              <j-dict-select-tag placeholder="请选择发货仓库" dictCode="logistics_shipping_warehouse"
                v-decorator="[
                  'queryParam.warehouse',
                  {rules: [{ required: true, message: '请选择发货仓库'}]}
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="目的地">
              <j-search-select-tag placeholder="请选择目的地" dict="hz_logistics_country_default,cn_name,code,logistics"
                v-decorator="[
                  'queryParam.destination',
                  {rules: [{ required: true, message: '请选择目的地'}]}
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="重量">
              <a-input-number placeholder="请输入重量" style="width: 100%;"
                v-decorator="[
                  'queryParam.weight',
                  {rules: [{ required: true, message: '请输入重量'}]}
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="计算日期">
              <j-date placeholder="请选择计算日期" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%"  
                v-decorator="[
                  'queryParam.calculateDate',
                  {rules: [{ required: true, message: '请选择计算日期'}]}
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="邮编">
              <a-input placeholder="请输入邮编" v-model="queryParam.zipCode" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="物流渠道">
              <j-search-select-tag ref="searchSelectTagRef" placeholder="请选择物流渠道" v-model="queryParam.channelId" :filterOption_="false" @handleSearch="handleSearch"></j-search-select-tag>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button v-has="'logisticsCostPrice:calculate'" type="primary" @click="calculate" icon="search">运费测算</a-button>
              <a-button type="primary" @click="searchReset_" icon="reload" style="margin-left: 8px">重置</a-button>
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a> -->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- table区域-begin -->
    <div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange"
        :customRow="selectRowData">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;" :preview="0"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail_(record)">详情</a>
          <!-- <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown> -->
        </span>

        <template slot="calculateFormSlot" slot-scope="text,record">
          <div class="templateSlot">
            <div v-for="(k,v) in text">
              <span>{{v}}：</span>
              <span>{{k}}</span>
            </div>
          </div>
        </template>
      </a-table>
    </div>

    <logistics-cost-price-calculate-result-modal ref="modalForm" @ok="modalFormOk"></logistics-cost-price-calculate-result-modal>
    <logistics-cost-price-modal ref="modalForm_" @ok="modalFormOk_"/>

  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import LogisticsCostPriceCalculateResultModal from './modules/LogisticsCostPriceCalculateResultModal'
  import {filterMultiDictText} from '@/components/dict/JDictSelectUtil'
  import { getAction } from '@api/manage'
  import { simpleDebounce } from '@/utils/util'
  import LogisticsCostPriceModal from '@/views/logistics/costPrice/modules/LogisticsCostPriceModal.vue'

  export default {
    name: 'LogisticsCostPriceCalculateResultList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      LogisticsCostPriceCalculateResultModal,
      LogisticsCostPriceModal
    },
    data () {
      return {
        description: '物流成本价计算结果管理页面',
        form: this.$form.createForm(this),
        disableMixinCreated: true,
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'渠道id',
            align:"center",
            dataIndex: 'channelNo'
          },
          {
            title:'成本价方案',
            align:"center",
            dataIndex: 'costPriceName'
          },
          {
            title:'物流商',
            align:"center",
            dataIndex: 'providerName'
          },
          {
            title:'渠道名称',
            align:"center",
            dataIndex: 'channelName'
          },
          {
            title:'计费分区',
            align:"center",
            dataIndex: 'classifyName'
          },
          {
            title:'计费重量',
            align:"center",
            dataIndex: 'weight'
          },
          {
            title:'计费模式',
            align:"center",
            dataIndex: 'calculateMethod_dictText'
          },
          {
            title:'成本价构成',
            align:"center",
            dataIndex: 'costPriceForm',
            scopedSlots: { customRender: 'calculateFormSlot' }
          },
          {
            title:'成本价估算',
            align:"center",
            dataIndex: 'estimatePrice',
            sorter: true,
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/logistics/calculate/logisticsCostPriceCalculateResult/list",
          delete: "/logistics/calculate/logisticsCostPriceCalculateResult/delete",
          deleteBatch: "/logistics/calculate/logisticsCostPriceCalculateResult/deleteBatch",
          exportXlsUrl: "/logistics/calculate/logisticsCostPriceCalculateResult/exportXls",
          importExcelUrl: "/logistics/calculate/logisticsCostPriceCalculateResult/importExcel",
          queryNameOrCodeChannel: "/logistics/channel/queryNameOrCode",
          costPriceList: "/logistics/costPrice/logisticsCostPrice/list",
        },

        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
    this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    watch: {
      toggleSearchStatus: {
        handler(val){
          if(val){
            this.handleSearch('');
          }
        }
      },
      'queryParam.channelId': {
        handler(val){
          if(!val){
            this.handleSearch('');
          }
        }
      }
    },
    methods: {
      initDictConfig(){
      },
      selectRowData(record,index){
        const that = this
        return {
          on:{
            dblclick:() => {
              // this.handleDetail(record)
            }
          }
        }
      },
      calculate(){
        this.form.validateFields((err, values) => {
          if(!err){
            let params = {
              ...this.queryParam,
              ...values.queryParam,
              ...this.isorter
            }
            getAction('/logistics/calculate/logisticsCostPriceCalculateResult/calculate/', params)
              .then((res)=>{
                if(res.success){
                  this.dataSource=res.result;
                  //this.$message.success(res.message)
                }else{
                  this.$message.warning(res.message)
                }
              })
          }
        })
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'warehouse',text:'发货仓',dictCode:'logistics_shipping_warehouse'})
        fieldList.push({type:'string',value:'destination',text:'目的地',dictCode:'hz_logistics_country_default,cn_name,id,logistics'})
        fieldList.push({type:'string',value:'channelId',text:'渠道',dictCode:'hz_logistics_channel,channel_name,id'})
        fieldList.push({type:'BigDecimal',value:'weight',text:'重量',dictCode:''})
        fieldList.push({type:'string',value:'zipCode',text:'邮编',dictCode:''})
        fieldList.push({type:'string',value:'costPriceId',text:'成本价方案',dictCode:''})
        fieldList.push({type:'string',value:'costPriceForm',text:'成本价构成',dictCode:''})
        fieldList.push({type:'BigDecimal',value:'estimatePrice',text:'成本价估算',dictCode:''})
        this.superFieldList = fieldList
      },
      searchQuery_(){
        this.calculate();
      },
      searchReset_(){
        this.form.resetFields();
        this.queryParam = {};
        this.dataSource = [];
      },
      handleSearch: simpleDebounce(function(likeParam){
        getAction(this.url.queryNameOrCodeChannel, { likeParam: likeParam.trim() }).then((res) => {
          if(res.success){
            let dictOptions = res.result && res.result.map(item => {
              return {
                value: item.id,
                text: item.channelName
              }
            })
            this.$refs.searchSelectTagRef.setCurrentDictOptions(dictOptions);
          }else{
            this.$message.warning(res.message);
          }
        })
      }, 200),
      handleTableChange(pagination, filters, sorter) {
        //分页、排序、筛选变化时触发
        //TODO 筛选
        console.log(pagination)
        if (Object.keys(sorter).length > 0) {
          this.isorter.column = sorter.field;
          this.isorter.order = "ascend" == sorter.order ? "asc" : "desc"
        }
        this.ipagination = pagination;
        this.calculate();
      },
      handleDetail_(record){
        //获取对应的成本价维护方案
        let params = {
          pageNo: 1,
          pageSize: 9999
        }
        getAction(this.url.costPriceList, params).then((res) => {
          if(res.success){
            let currentRecord = res.result && res.result.records && res.result.records.filter(item => item.id == record.costPriceId);
            if(currentRecord && currentRecord.length){
              this.$refs.modalForm_.edit(currentRecord[0]);
              this.$refs.modalForm_.title="详情";
              this.$refs.modalForm_.disableSubmit = true;
            }
          }else{
            this.$message.warning(res.message);
          }
        })
      },
      modalFormOk_() {
        // 新增/修改 成功时，重载列表
        this.calculate();
        //清空列表选中
        this.onClearSelected()
      },
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>